package controllers

import (
	"beego/comm/auth"
	"beego/comm/utils"
	"fmt"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

const (
	ROOT_USER = "root"
)

type PageQueryController struct {
	beego.Controller
}

func isInStrSlice(arr []string, str string) bool {
	for i := 0; i < len(arr); i++ {
		if arr[i] == str {
			return true
		}
	}
	return false
}

func (c *PageQueryController) PageQuery() {
	beego.Info("================= PageQuery start =================")
	result := map[string]interface{}{
		"curPage":   "",
		"curName":   "",
		"subPage":   nil,
		"prtPage":   nil,
		"errorInfo": "",
	}
	c.Data["json"] = result
	defer func() {
		err := recover()
		if nil != err {
			result["error"] = err
			c.ServeJSON()
		}
	}()
	resmap := auth.HandleLogin(c.Ctx.Input.RequestBody)
	user_name := utils.CheckFieldExists(resmap, "userName")
	cur_page_old := utils.CheckFieldExists(resmap, "curPage")
	cur_page := cur_page_old
	o := orm.NewOrm()
	var maps []orm.Params
	sql := fmt.Sprintf("select page_path from page_role where role in (select role_name from user_role where user_name='%s')", user_name)
	beego.Info(sql)
	o.Raw(sql).Values(&maps)
	var role_page_arr []string
	for i := 0; i < len(maps); i++ {
		role_page_arr = append(role_page_arr, string(maps[i]["page_path"].(string)))
	}
	o.Raw(`select page_path,page_name from page_dir where parent_page_id in (
		select page_id from page_dir where page_path = ?)`).SetArgs(cur_page).Values(&maps)
	subPage := make([]map[string]string, 0)
	prtPage := make([]map[string]string, 0)
	for i := 0; i < len(maps); i++ {
		item := make(map[string]string)
		for k, v := range maps[i] {
			item[k] = string(v.(string))
		}
		if ROOT_USER == user_name || true == isInStrSlice(role_page_arr, item["page_path"]) {
			subPage = append(subPage, item)
		}
	}
	for i := 0; i < 5; i++ {
		o.Raw(`select page_path, page_name from page_dir where page_id in (
			select parent_page_id from page_dir where page_path = ?)`).SetArgs(cur_page).Values(&maps)
		if 0 == len(maps) {
			panic("")
		}
		item := make(map[string]string)
		end := false
		for k, v := range maps[0] {
			item[k] = string(v.(string))
			if "page_path" == k {
				cur_page = item[k]
				if "/" == cur_page {
					end = true
				}
			}
		}
		if end {
			break
		}
		if ROOT_USER == user_name || true == isInStrSlice(role_page_arr, item["page_path"]) {
			prtPage = append([]map[string]string{item}, prtPage...)
		}
	}
	c.Data["json"] = map[string]interface{}{
		"curPage":   cur_page_old,
		"curName":   "",
		"subPage":   subPage,
		"prtPage":   prtPage,
		"errorInfo": "",
	}
	c.ServeJSON()
	beego.Info("================= PageQuery end =================")
}
